/* eslint-disable consistent-return */
import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, Select, message, Button, Table } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import { getArryStringBySymbol } from '@/utils/utils';
import Supplier from '../../components/NsSupplier';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ loading, changeprot }) => ({
  loading: loading.models.changeprot || false,
  changeprot,
}))
@Form.create()
class BasicForm extends React.PureComponent {
  componentDidMount() {
    // 获取当前角色所在公司对应的平台供应商
    const {
      dispatch,
      changeprot: { isGoBack = false },
    } = this.props;
    if (!isGoBack) {
      dispatch({
        type: 'changeprot/updateQuery',
        payload: {
          changeType: '1',
          suppId: undefined,
          suppProtId: undefined,
          oldSuppId: undefined,
        },
      });
      dispatch({
        type: 'changeprot/updateModelData',
        payload: {
          supplyList: [],
          protList: [],
        },
      });
    }
    dispatch({
      type: 'changeprot/updateModelData',
      payload: {
        isGoBack: false,
      },
    });
  }

  // 更换类型
  changeType = e => {
    const { form, dispatch } = this.props;
    form.resetFields(['suppId', 'suppProtId']);
    dispatch({
      type: 'changeprot/updateQuery',
      payload: {
        changeType: e.target.value,
        suppId: undefined,
        suppProtId: undefined,
      },
    });
    dispatch({
      type: 'changeprot/updateModelData',
      payload: {
        protList: [],
      },
    });
  };

  // 选择供应商 : 根据选择显示不同
  selectCompany = suppId => {
    const { form, dispatch } = this.props;
    form.resetFields(['suppProtId']);
    dispatch({
      type: 'changeprot/updateQuery',
      payload: {
        suppId,
        suppProtId: undefined,
      },
    });
    dispatch({
      type: 'changeprot/updateModelData',
      payload: {
        protList: [],
      },
    });
    dispatch({
      type: 'changeprot/fetchProtList',
      payload: {
        validFlag: 1,
        recvSuppId: suppId,
        pagerArg: { currentPage: 1, pageSizes: 999 },
      },
    });
  };

  // 选择协议
  selectProt = (suppProtId, options) => {
    const { dispatch } = this.props;
    const protInfo = (options.props && options.props.fsOptions) || null;
    dispatch({
      type: 'changeprot/updateModelData',
      payload: { custName: '', areaName: '', detList: [] },
    });
    if (protInfo) {
      const areaName = getArryStringBySymbol(protInfo.areaList, 'areaName');
      const detList = [];
      if (protInfo.packList && protInfo.packList.length) {
        protInfo.packList.forEach(item => {
          const obj = {};
          if (item.detList && item.detList.length) {
            obj.pdName = getArryStringBySymbol(item.detList, 'pdName', '、');
            obj.pdId = getArryStringBySymbol(item.detList, 'pdId', '_');
            obj.fee =
              item.detList.reduce((total, currentValue) => total + currentValue.fee || 0, 0) || 0;
          }
          detList.push(obj);
        });
      }
      dispatch({
        type: 'changeprot/updateQuery',
        payload: { suppProtId },
      });
      dispatch({
        type: 'changeprot/updateModelData',
        payload: { custName: protInfo.custName, areaName, detList },
      });
    } else {
      message.warning('该供应商协议数据有误！');
    }
  };

  // 下一步
  nextStep = () => {
    Object.entries({ a: 2, b: 3, c: 4 }).forEach(([key, values]) => {
      console.log(key, 'key', values, 'values');
    });
    const { form, onNext, dispatch } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.changeType === '2' && values.oldSuppId === values.suppId) {
          return message.warning('原供应商与新供应商不应该相同');
        }
        const temp = values;
        Object.keys(temp).forEach(key => {
          if (temp[key] && temp[key].key) {
            temp[key] = temp[key].key;
          } else {
            temp[key] = temp[key] || '';
          }
        });

        delete temp.area;
        delete temp.custName;
        const protInfo = { ...temp };
        dispatch({
          type: 'changeprot/updateQuery',
          payload: protInfo,
        });
        onNext(protInfo);
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      batchQuery,
      changeprot: { protList, custName, areaName, detList },
      loading,
    } = this.props;
    const sumPrice = detList.reduce((total, currentValue) => total + currentValue.fee || 0, 0) || 0;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const columns = [
      {
        title: '产品',
        dataIndex: 'pdName',
        align: 'center',
        render: val => (val === 'undefined' ? '--' : val),
      },
      {
        title: `价格 (总价：${sumPrice && sumPrice.toFixed(2)})`,
        dataIndex: 'fee',
        align: 'right',
        render: val => (val && val.toFixed(2)) || '--',
      },
    ];
    return (
      <Form style={{ margin: '40px auto 0', maxWidth: 800 }}>
        <Spin tip="Loading..." spinning={loading}>
          <FormItem {...formItemLayout} label="更换内容">
            {getFieldDecorator('changeType', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.changeType,
            })(<DictCode inputType="3" dictType="CHANGE_PROT_TYPE" onChange={this.changeType} />)}
          </FormItem>
          {batchQuery.changeType === '2' && (
            <FormItem {...formItemLayout} label="原供应商">
              {getFieldDecorator('oldSuppId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: batchQuery.oldSuppId,
              })(<Supplier params={{ status: 2 }} isClearData={false} />)}
            </FormItem>
          )}
          <FormItem
            {...formItemLayout}
            label={batchQuery.changeType === '1' ? '供应商' : '新供应商'}
          >
            {getFieldDecorator('suppId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.suppId,
            })(
              <Supplier params={{ status: 2 }} getData={this.selectCompany} isClearData={false} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="新供应商协议">
            {getFieldDecorator('suppProtId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: batchQuery.suppProtId,
            })(
              <Select
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                onChange={this.selectProt}
              >
                {protList.map(item => (
                  <Option key={item.suppProtId} fsOptions={item} title={item.suppProtName}>
                    {item.suppProtName}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          {batchQuery.suppProtId && (
            <FormItem {...formItemLayout} label="客户名称">
              {getFieldDecorator('custName', {
                rules: [{ required: false }],
              })(<span>{custName || '--'}</span>)}
            </FormItem>
          )}
          {batchQuery.suppProtId && (
            <FormItem {...formItemLayout} label="执行地区">
              {getFieldDecorator('area', {
                rules: [{ required: false }],
              })(<span>{areaName}</span>)}
            </FormItem>
          )}
          {batchQuery.suppProtId && (
            <Table
              style={{ width: 450, margin: '0 auto' }}
              columns={columns}
              dataSource={detList}
              rowKey="pdId"
              bordered
              size="middle"
              pagination={false}
            />
          )}
          <div style={{ marginTop: 100, textAlign: 'center' }}>
            <Button
              onClick={() => router.push('/sendordermanage/adjusttask/index')}
              style={{ marginRight: 8 }}
            >
              返回
            </Button>
            <Button type="primary" onClick={this.nextStep}>
              下一步
            </Button>
          </div>
        </Spin>
      </Form>
    );
  }
}

export default BasicForm;
